import React, { Component, Fragment } from 'react';
import {
  NativeModules,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  TextInput,
  ImageBackground,
  Platform,
} from 'react-native';
import obj from '../../common/utils/obj';
import colors from '../../common/colors';
import { uploadImage } from '../../config';
import user from '../../api/user';
import { msg } from '../../common';
import { px2dp } from '../../common/styles';
import { iconCamera } from '../../image';

/**
 * @author kanglang
 * @description 绑定广发联名卡
 * @createDate 2020/6/24
 *
 */
export default class BindCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cardNo: '',
      status: 0,
    };
  }

  // 选择图片
  uploadBankcard = () => {
    this.setState({
      cardNo: '',
      bankcardImage: '',
      status: 0,
    });
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.IdCardUpload(path);
    });
  };

  // 上传图片到oss
  IdCardUpload(path) {
    this.setState({ cardNo: '' });
    NativeModules.WindowModule.showLoading();
    uploadImage('upload?dirName=bankcard', path)
      .then((res) => {
        // 请求成功
        if (res.success) {
          this.setState({
            bankcardImage: { uri: res.data.url },
          });
          this.toRecognitionBankcard(res.data.url);
        } else {
          NativeModules.WindowModule.showWindow(
            { content: '上传失败，请重试', onlyRightBtn: '1' },
            (e) => {},
          );
        }
        NativeModules.WindowModule.dismissLoading();
      })
      .catch((err) => {
        NativeModules.WindowModule.dismissLoading();
        // 请求失败
        NativeModules.WindowModule.showWindow(
          { content: '上传出错，请重试', onlyRightBtn: '1' },
          (e) => {},
        );
      });
  }

  // 去识别
  toRecognitionBankcard = (path) => {
    user.bankcardOCR({ fileUrl: path }).then((res) => {
      if (res.success) {
        this.setState({
          cardNo: res.data,
          status: 1,
        });
      } else {
        this.setState({
          status: 2,
        });
        NativeModules.WindowModule.showWindow(
          {
            title: '温馨提示',
            content: res.msg,
            rightStr: '我知道了',
            onlyRightBtn: '1',
          },
          (e) => {
            if (e == 1) {
              this.setState({
                bankcardImage: '',
                status: 0,
              });
            }
          },
        );
      }
    });
  };

  // 去绑卡
  toBindCard = () => {
    const { cardNo } = this.state;
    if (!cardNo) {
      return;
    }
    user.addbankCard({ bankCardNo: cardNo }).then((res) => {
      if (res.success) {
        msg.emit('app:tip', { text: '绑定成功' });
        msg.emit('router: refreshRoute', {
          routeName: 'CertificationProgress',
        });
        msg.emit('router: back');
      } else {
        NativeModules.WindowModule.showWindow(
          {
            title: '温馨提示',
            content: res.msg,
            rightStr: '我知道了',
            onlyRightBtn: '1',
          },
          (e) => {
            if (e == 1) {
              this.setState({
                cardNo: '',
                bankcardImage: '',
                status: 0,
              });
            }
          },
        );
      }
    });
  };

  bankcardImg = () => {
    const { bankcardImage } = this.state;
    if (bankcardImage) {
      return bankcardImage;
    }
    return require('../../image/icons/icon_cardbg.png');
  };

  statusView = () => {
    const { status } = this.state;
    if (status == 0) {
      return (
        <>
          <Text style={styles.scanTips}>点击拍摄或上传卡号面</Text>
        </>
      );
    }
    return (
      <>
        <View style={styles.statusIconWrap}>
          <Text style={styles.statusTips}>
            {status == 1 ? '识别成功' : '识别失败，点击图片重新上传'}
          </Text>
          <Image
            style={styles.statusIcon}
            resizeMode='stretch'
            source={
              status == 1
                ? require('../../image/icons/icon_success_green.png')
                : require('../../image/icons/icon_error.png')
            }
          />
        </View>
        <Text style={styles.scanTipError}>
          {status == 1
            ? '点击图片即可重新上传'
            : '请上传清晰、完整有卡号面的广发联名卡'}
        </Text>
      </>
    );
  };

  render() {
    const { cardNo, bankcardImage } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.main}>
          <View style={styles.bankWrap}>
            <TouchableOpacity
              activeOpacity={0.8}
              style={styles.cameraBtn}
              onPress={this.uploadBankcard}
            >
              <ImageBackground
                style={styles.cameraBg}
                source={this.bankcardImg()}
              >
                {!bankcardImage ? (
                  <Image
                    style={styles.cameraIcon}
                    resizeMode='stretch'
                    source={iconCamera}
                  />
                ) : null}
              </ImageBackground>
              <View style={styles.scanWrap}>{this.statusView()}</View>
            </TouchableOpacity>
          </View>

          <View style={styles.textWrap}>
            <Text style={styles.textTitle}>银行卡号</Text>
            <TextInput
              editable={false}
              placeholder='请添加银行卡照片识别'
              placeholderTextColor='#666562'
              style={styles.textInput}
              onChangeText={() => {}}
              value={cardNo}
            />
          </View>
        </View>
        <TouchableOpacity
          activeOpacity={1}
          style={[
            styles.button,
            cardNo
              ? {
                backgroundColor: colors.active,
              }
              : {
                backgroundColor: colors.notActive,
              },
          ]}
          onPress={this.toBindCard}
        >
          <Text style={styles.white}> 下一步 </Text>
        </TouchableOpacity>
      </View>
    );
  }

  onChangeValue(text) {
    this.setState({ value: text });
  }

  _handleBack() {
    const { navigator } = this.props;
    if (navigator && navigator.getCurrentRoutes().length > 1) {
      navigator.pop();
      return true;
    }
    return false;
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    height: '100%',
  },
  main: {
    marginTop: px2dp(12) * 2,
  },
  textWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    height: px2dp(50) * 2,
    marginTop: px2dp(12) * 2,
    backgroundColor: '#FFFFFF',
    paddingLeft: px2dp(16) * 2,
    paddingRight: px2dp(16) * 2,
  },
  textTitle: {
    color: '#333232',
    fontSize: px2dp(14) * 2,
  },
  textInput: {
    flex: 1,
    height: px2dp(50) * 2,
    color: '#666564',
    fontSize: px2dp(14) * 2,
    textAlign: 'right',
  },
  button: {
    color: '#fff',
    padding: px2dp(12) * 2,
    textAlign: 'center',
    width: '80%',
    height: px2dp(48) * 2,
    borderRadius: px2dp(8) * 2,
    marginLeft: '10%',
    bottom: obj.STATUSBAR_HEIGHT + px2dp(40) * 2,
    position: 'absolute',
    justifyContent: 'center',
  },
  white: {
    color: '#fff',
    textAlign: 'center',
  },
  bankWrap: {
    width: '100%',
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  cameraBtn: {
    paddingBottom: px2dp(20) * 2,
    paddingTop: px2dp(20) * 2,
  },
  cameraBg: {
    width: px2dp(270) * 2,
    height: px2dp(160) * 2,
    justifyContent: 'center',
    alignItems: 'center',
    alignItems: 'center',
  },
  cameraIcon: {
    justifyContent: 'center',
    alignItems: 'center',
    height: px2dp(72) * 2,
    width: px2dp(72) * 2,
  },
  scanWrap: {
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: px2dp(12) * 2,
  },
  scanTips: {
    fontSize: px2dp(14) * 2,
    color: '#999796',
  },
  scanTipError: {
    color: '#999896',
    fontSize: px2dp(12) * 2,
  },
  statusIconWrap: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: px2dp(6) * 2,
  },
  statusTips: {
    fontSize: px2dp(14) * 2,
    color: '#343332',
  },
  statusIcon: {
    width: px2dp(16) * 2,
    height: px2dp(16) * 2,
    marginLeft: px2dp(4) * 2,
  },
});
